﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxFormLayout;
using DispatcherWebAppModel;

public partial class Default2 : System.Web.UI.Page
{
    DispatcherWebAppEntities context = new DispatcherWebAppEntities();
    string selectquery;

    protected void Page_Load(object sender, EventArgs e)
    {
        SuonUtil su = new SuonUtil();
        bool dispEnable = su.isDispEnable;
        if (!dispEnable) Response.Redirect("~/");

        PrepareJobTypeID();
        selectquery = ds_request.SelectCommand;
        if (dt1.Value == null || dt2.Value == null)
        {
            dt1.Value = DateTime.Now;
            dt2.Value = DateTime.Now;
            //if (Session["dt1"] != null) { dt1.Value = Session["dt1"]; } else { dt1.Value = DateTime.Now; }
            //if (Session["dt2"] != null) { dt2.Value = Session["dt2"]; } else { dt2.Value = DateTime.Now; }
            return;
        }
        open_Request();

    }
    protected void btn_find_Click(object sender, EventArgs e)
    {
        // TabbedLayoutGroup group = (TabbedLayoutGroup)ASPxFormLayout1.Items[0];
        // group.PageControl.ActiveTabIndex = 1;
        if (IsPostBack)
            open_Request();
    }

    //IQueryable query;
    protected void open_Request()
    {
        //DateTime d2 = dt2.Date.AddHours(23).AddMinutes(59);
        //houseID.Value = 43;

        //var query = from r in context.Rq_Request
        //            join c in context.Rq_Comment on r.LastKeyCommentId equals c.CommentId
        //            where (r.IssuedAtUtc >= dt1.Date & r.IssuedAtUtc <= d2)
        //            select r;
        ////добавляем динамические условия
        //if (houseID.Value != null) 
        //{
        //    int house = Convert.ToInt32(houseID.Value);
        //    query = query.Where(a => a.HouseId == house); 
        //}
        //grd1.DataSource = query.ToList();
        //grd1.DataBind();
        ldpanel.Visible = true;
        if (dt1.Value == null || dt2.Value == null) { return; }

        DateTime d1 = dt1.Date;
        DateTime d2 = dt2.Date;

        //houseID.Value = 43;
        //JobTypeID.Value = 4;

        Session["dt1"] = d1.AddHours(00).AddMinutes(00).ToUniversalTime();
        Session["dt2"] = d2.AddHours(23).AddMinutes(59).ToUniversalTime();

        if (houseID.Value != null)
        {
            selectquery += String.Format(" and (rq.HouseId ={0})", houseID.Value);
        }
        else
        {
            if (cbb_Street.Value != null)
            {
                string houseList = GetHouseByStreet((int)cbb_Street.Value);
                if (houseList != string.Empty)
                { selectquery += String.Format(" and (rq.HouseId in ({0}))", houseList); }
            }
        }
        if (flatID.Value != null)
        {
            selectquery += String.Format(" and (rq.Apartment = '{0}')", flatID.Value);
        }
        if (JobTypeID.Value != null)
        {
            selectquery += String.Format(" and (rq.JobTypeId ={0})", JobTypeID.Value);
        }
        if (JobTypeSubID.Value != null)
        {
            selectquery += String.Format(" and (rq.JobSubtypeId ={0})", JobTypeSubID.Value);
        }
        if (LocationID.Value != "-1")
        {
            selectquery += String.Format(" and (rq.Location ={0})", LocationID.Value);
        }
        if (StatusID.Value != "-1")
        {
            selectquery += String.Format(" and (rq.[Status] ={0})", StatusID.Value);
        }

        selectquery += String.Format(" and (rq.WorkCompanyId = {0})", Profile.UserInfo.disp.Kontragent);

        ds_request.SelectCommand = selectquery;
        grd1.DataSource = ds_request;
        grd1.DataBind();
        ldpanel.Visible = false;
    }

    private string GetHouseByStreet(int street)
    {
        string s = string.Empty;
        var query = from h in context.Geo_House
                    where h.StreetId == street
                    select h.HouseId;
        foreach (var item in query)
        {
            if (s == string.Empty) { s = item.ToString(); }
            else { s += "," + item.ToString(); }
        }
        return s;
    }

    protected void grd1_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
    {
        if (e.Column.FieldName == "CreatedAtUtc")
        {
            //e.Value = DateTime.SpecifyKind((DateTime)e.Value, DateTimeKind.Utc);
        }
    }
    protected void grd1_HtmlDataCellPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableDataCellEventArgs e)
    {
        if (e.DataColumn.FieldName == "State")
        {
            int value = Convert.ToInt32(e.GetValue("Status"));

            switch (value)
            {
                case 1: //Не рассмотрена
                    e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#ffb6c1");
                    //e.Cell.ForeColor = System.Drawing.Color.White;
                    break;
                case 2: //В процессе
                    e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#ffffb3");
                    //e.Cell.ForeColor = System.Drawing.Color.White;
                    break;
                case 3: //Выполнена
                    e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#90ee90");
                    //e.Cell.ForeColor = System.Drawing.Color.White;
                    break;
                case 4: //Возвращена
                    e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#ffb6c1");
                    break;
                case 5: //Снята
                    e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#1e90ff");
                    e.Cell.ForeColor = System.Drawing.Color.White;
                    break;
                case 6: //Закрыта
                    e.Cell.BackColor = System.Drawing.Color.Green;
                    e.Cell.ForeColor = System.Drawing.Color.White;
                    break;
                case 7: //Отложена
                    e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#87ceeb");
                    break;
                case 8: //Текущий ремонт
                    e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#69c");
                    e.Cell.ForeColor = System.Drawing.Color.White;
                    break;
                case 9: //Запрос в службу эксплуатации (СЭ)
                    e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#369");
                    e.Cell.ForeColor = System.Drawing.Color.White;
                    break;
            }
        }
    }
    protected void grd1_CustomColumnDisplayText(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDisplayTextEventArgs e)
    {
        //var dt = TimeZone.CurrentTimeZone.ToLocalTime((DateTime)e.Value);
        if (e.Column.FieldName == "RequestId") { return; }
        string s, s1, s2;
        if (e.Value != null)
        {
            s = e.Value.ToString();
            s1 = s.Replace("`", "<br>");
            s2 = s1.Replace("^", "<hr />");
            e.DisplayText = s2;
            //+ "<hr />" + e.GetFieldValue("RequestId")
        }
        //switch (e.Column.FieldName)
        //{
        //    case "CreatedAtUtc":
        //        s = TimeZone.CurrentTimeZone.ToLocalTime((DateTime)e.Value).ToString("dd.MM.yyyy HH:mm");
        //        e.DisplayText = s;
        //        break;
        //    case "IssuedAtUtc":
        //        e.DisplayText = TimeZone.CurrentTimeZone.ToLocalTime((DateTime)e.Value).ToString("dd.MM.yyyy HH:mm");
        //        break;
        //    case "DueDateUtc":
        //        e.DisplayText = TimeZone.CurrentTimeZone.ToLocalTime((DateTime)e.Value).ToString("dd.MM.yyyy HH:mm");
        //        break;
        //    case "CompletedAtUtc":
        //        if (e.Value != null)
        //        {
        //            s = TimeZone.CurrentTimeZone.ToLocalTime((DateTime)e.Value).ToString("dd.MM.yyyy HH:mm");
        //            e.DisplayText = s;
        //        }
        //        break;
        //    case "DU":
        //        if (e.Value != null)
        //        {                    
        //            s = e.Value.ToString();
        //            s1 = s.Replace("`","<br>");
        //            e.DisplayText = s1;
        //        }
        //        break;
        //}
    }
    protected void ASPxButton2_Click(object sender, EventArgs e)
    {
        dt1.Value = null;
        dt2.Value = null;
    }

    protected void FillJobSubtype(ASPxComboBox combo, int ID)
    {
        combo.DataSourceID = "ds_JobSubtype";
        combo.ValueField = "JobSubtypeId";
        combo.TextField = "Title";
        ds_JobSubtype.SelectParameters["JobTypeId"].DefaultValue = ID.ToString();
        combo.DataBindItems();

        combo.Items.Insert(0, new ListEditItem("[ВСЕ]", null)); // Null Item
    }

    protected void JobTypeSubID_Callback(object sender, CallbackEventArgsBase e)
    {
        //int ID = Convert.ToInt32(JobTypeID.Value);
        //FillJobSubtype(JobTypeSubID, ID);

        //ASPxComboBox JobTypeSubID = (ASPxComboBox)sender;
        // AccessDataSource cmbChildAccessDataSource = (AccessDataSource)cmbChild.NamingContainer.FindControl("asdChild");
        ds_JobSubtype.SelectParameters["JobTypeId"].DefaultValue = e.Parameter;
        JobTypeSubID.DataBindItems();

        JobTypeSubID.Items.Insert(0, new ListEditItem("[ВСЕ]", null)); // Null Item
    }

    protected void PrepareJobTypeID()
    {
        JobTypeID.Items.Clear();
        JobTypeID.DataBindItems();
        JobTypeID.Items.Insert(0, new ListEditItem("[ВСЕ]", null)); // Null Item

        cbb_Street.Items.Clear();
        cbb_Street.DataBindItems();
        cbb_Street.Items.Insert(0, new ListEditItem("[ВСЕ]", null)); // Null Item
    }

    protected void houseID_Callback(object sender, CallbackEventArgsBase e)
    {
        ldpanel.Enabled = true;
        ds_house.SelectParameters["StreetId"].DefaultValue = e.Parameter;
        houseID.DataBindItems();
        houseID.Items.Insert(0, new ListEditItem("[ВСЕ]", null)); // Null Item
    }
}